//
//  MGRecordAccessor.m
//  MoneyGoal_iOS
//
//  Created by yyb on 2022/9/3.
//  Copyright © 2022 Moneyease CO,. LTD. All rights reserved.
//

#import "MGRecordAccessor.h"

@implementation MGRecordAccessor

+ (MGRecordAccessor *)shared
{
    static MGRecordAccessor *manager = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manager = [[MGRecordAccessor alloc] init];
    });
    return manager;
}

- (Class)getAccessorClass
{
    return [MGRecordModel class];
}

- (NSString *)getAccessorDirPath
{
    return RECORD_CACHE_PATH;
}

- (NSString *)getAccessorDefaultPath
{
    return @"Records";
}

- (NSString *)getOssPrefix
{
    return [NSString stringWithFormat:@"%@/records/", [MGUserModel user].uid];;
}

- (void)beginInitialize
{
    Class dataClass = [self getAccessorClass];
    NSString *path = [NSBundle.mainBundle pathForResource:[self getAccessorDefaultPath] ofType:@"txt"];
    NSData *data = [NSFileManager.defaultManager contentsAtPath:path];
    if (data) {
        self.dataModels = [NSArray yy_modelArrayWithClass:dataClass json:data].mutableCopy;
        [self saveToLocalWithDataModels:self.dataModels completeBlock:nil];
    }
}

- (MGRecordModel *)getDefaultRecordModel
{
    for (MGRecordModel *dataModel in self.dataModels) {
        if (dataModel.uniqueId == UNIQUE_ID_CANUPLOAD) {
            return dataModel;
        }
    }
    return nil;
}

- (void)mergeDefaultRecordModelsWithCompleteBlock:(nonnull YYBTapedActionBlock)completeBlock errorBlock:(nonnull YYBErrorBlock)errorBlock
{
    // 找出线上已存储的那个默认账本
    MGRecordModel *recordModel = nil;
    NSMutableArray *otherDefaultModels = [NSMutableArray new];
    for (MGRecordModel *dataModel in self.dataModels) {
        if (dataModel.uniqueId == UNIQUE_ID_CANUPLOAD) {
            if (dataModel.create_userId.isExist) {
                recordModel = dataModel;
            } else {
                [otherDefaultModels addObject:dataModel];
            }
        }
    }
    
    if (recordModel) {
        for (MGRecordModel *otherDefaultModel in otherDefaultModels) {
            [recordModel.receiptModels addObjectsFromArray:otherDefaultModel.receiptModels.mutableCopy];
        }
        [self saveToOssAndLocalWithDataModels:@[recordModel] completeBlock:^{
            for (MGRecordModel *recordModels in otherDefaultModels) {
                [self deleteLocalDataModel:recordModels completeBlock:^{
                    
                } errorBlock:errorBlock];
            }
            if (completeBlock) {
                completeBlock();
            }
        } errorBlock:errorBlock];
    } else {
        // 刚登陆的账号没有存储过记录，本地有记录
        if (otherDefaultModels.count == 1) {
            MGRecordModel *defaultRecordModel = otherDefaultModels[0];
            if (defaultRecordModel.uniqueId == UNIQUE_ID_CANUPLOAD) {
                [self saveToOssWithDataModels:@[defaultRecordModel] completeBlock:^{
                    if (completeBlock) {
                        completeBlock();
                    }
                } errorBlock:errorBlock];
            }
        }
    }
}

// ===========================================================
- (MGRecordModel *)getSelectedRecordModel
{
    NSMutableArray *dataModels = [self.dataModels mutableCopy];
    [dataModels sortUsingComparator:^NSComparisonResult(MGRecordModel * obj1, MGRecordModel * obj2) {
        return obj1.selected_at < obj2.selected_at;
    }];
    
    if (dataModels.count > 0) {
        return dataModels.firstObject;
    }
    return nil;
}

- (void)selectRecordModel:(MGRecordModel *)recordModel
{
    if (recordModel) {
        recordModel.selected_at = [NSDate date].timeIntervalSince1970;
    }
    [self saveToLocalWithDataModels:self.dataModels completeBlock:nil];
}

- (void)createReceiptModel:(MGReceiptModel *)receiptModel recordModel:(MGRecordModel *)recordModel completeBlock:(YYBTapedActionBlock)completeBlock errorBlock:(nonnull YYBErrorBlock)errorBlock
{
    [MGCategoryAccessor.shared riseReferenceWithUniqueId:receiptModel.categoryUniqueId];
    [MGAccountAccessor.shared riseReferenceWithUniqueId:receiptModel.accountUniqueId];
    
    [recordModel.receiptModels addObject:receiptModel];
    [self saveToOssAndLocalWithDataModels:@[recordModel] completeBlock:completeBlock errorBlock:errorBlock];
}

- (void)updateReceiptModel:(MGReceiptModel *)receiptModel shouldUpdateModel:(MGReceiptModel *)shouldUpdateModel recordModel:(MGRecordModel *)recordModel completeBlock:(YYBTapedActionBlock)completeBlock errorBlock:(YYBErrorBlock)errorBlock
{
    NSInteger index = [recordModel.receiptModels indexOfObject:receiptModel];
    [recordModel.receiptModels replaceObjectAtIndex:index withObject:shouldUpdateModel];
    
    [self saveToOssAndLocalWithDataModels:@[recordModel] completeBlock:completeBlock errorBlock:errorBlock];
}

- (void)deleteReceiptModel:(MGReceiptModel *)receiptModel recordModel:(MGRecordModel *)recordModel completeBlock:(YYBTapedActionBlock)completeBlock errorBlock:(YYBErrorBlock)errorBlock
{
    [recordModel.receiptModels removeObject:receiptModel];
    
    [self saveToOssAndLocalWithDataModels:@[recordModel] completeBlock:completeBlock errorBlock:errorBlock];
}

- (NSDecimalNumber *)sumMoneyOfReceiptModels:(NSArray *)receiptModels
{
    NSDecimalNumber *num = [[NSDecimalNumber alloc] initWithString:@"0"];
    for (MGReceiptModel *dataModel in receiptModels) {
        // 两位小数点后，只舍不入
        NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
        if (dataModel.savedMoney) {
            num = [num decimalNumberByAdding:dataModel.savedMoney withBehavior:roundUp];
        }
    }
    return num;
}

@end
